export interface metaType {
    title?: string; needLogin?: boolean;
}
export interface routeType {
    path: string;
    component?: any;
    children?: Array<routeType>;
    meta?: metaType;
    redirect?: string;
    name?: string;
}
//手写路由表
/* const routes: Array<routeType> = [
    {
        path: '/',
        redirect: '/Home',
    }, {
        path: '/Home',
        component: () => import('@/pages/Home'),
        meta: {
            title: "首页",
        },
        children: [],
    }, {
        path: '/About',
        component: () => import('@/pages/About'),
        meta: {
            title: "关于",
        }
    }, {
        path: '/Login',
        component: () => import('@/pages/Login'),
        meta: {
            title: "登录",
        }
    }, {
        path: '*',
        component: () => import('@/pages/NotFound'),
    }
]
export default routes */

//约定大约配置，自动生成路由表
const rootRoute: routeType = {
    //根路由
    path: '/',
    redirect: '/Home',
};
const notFoundRoute: routeType = {
    //404
    path: '*',
    component: () => import('@/pages/NotFound'),
};

const pages = import.meta.glob("../pages/**/page.ts", {
    eager: true,
    import: 'default',
});
const pageComps = import.meta.glob("../pages/**/index.tsx")//拿page组件

function handleRoutes(path: string, meta: metaType): routeType {
    let pageJSPath = path
    path = path.replace(/\.\.\/pages|\/page\.ts/g, '');
    let children: routeType[] = []
    path = path || '/'
    const name = path.split('/').filter(Boolean).pop() || 'Home' //去空格
    const compPath = pageJSPath.replace('page.ts', 'index.tsx')
    return {
        path,
        name,
        component: pageComps[compPath],
        children,
        meta,
    }
}

// 处理嵌套路由
function handleNestedRoutes(routes: routeType[]): routeType[] {
    const routeMap: { [key: string]: routeType } = {};//路由映射
    routes.forEach(route => {
        routeMap[route.path] = route;
    });
    // 遍历所有路由，将每个路由添加到其父路由的children数组中
    routes.forEach(route => {
        const parentPath = route.path.substring(0, route.path.lastIndexOf('/'));
        if (routeMap[parentPath]) {
            routeMap[parentPath].children?.push(route);
        }
    });
    // 返回只包含顶级路由的数组
    return routes.filter(route => !route.path.substring(0, route.path.lastIndexOf('/')).includes('/'));
}
const routes: routeType[] = handleNestedRoutes(Object.entries(pages).map(([path, meta]) => handleRoutes(path, meta as metaType)));

console.log('最终生成的路由', routes);

const AutoGeneratedRoutes: routeType[] = [rootRoute, ...routes, notFoundRoute]
export default AutoGeneratedRoutes;
